package com.yang.utils;

import com.yang.bean.MarketAdmin;
import com.yang.bean.MarketUser;
import com.yang.exception.WXException;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName UserUtil
 * @Description TODO
 * @Author zhangdongdong
 * @Date 2022/9/10 22:24
 * @Version 1.0
 */
public class UserUtil {

    public static MarketUser getUserMsg(HttpServletRequest request, DefaultWebSessionManager defaultWebSessionManager) {
        //需要获取登录的用户信息
        String header = request.getHeader("X-CskaoyanMarket-Token");
        //需要获取登录的用户信息
        MarketUser marketUser = null;
        try {
            Session session = defaultWebSessionManager.getSession(() -> header);
            marketUser = (MarketUser) session.getAttribute(header);
        } catch (Exception e) {
            throw new WXException("session丢失");
        }
        return marketUser;
    }


    public static MarketAdmin getAdminMsg(HttpServletRequest request, DefaultWebSessionManager defaultWebSessionManager) {
        //需要获取登录的用户信息
        String header = request.getHeader("X-CskaoyanMarket-Admin-Token");
        //需要获取登录的用户信息
        MarketAdmin marketAdmin = null;
        try {
            Session session = defaultWebSessionManager.getSession(() -> header);
            marketAdmin = (MarketAdmin) session.getAttribute(header);
        } catch (Exception e) {
            throw new WXException("session丢失");
        }
        return marketAdmin;
    }

    /** 
     * @description: 用户登陆时返回该用户id，未登录则返回0
     * @param: request
defaultWebSessionManager
     * @return: java.lang.Integer
     * @author zhangdongdong
     * @date: 2022/9/12 17:26
     */ 
    public static Integer getUserId(HttpServletRequest request, DefaultWebSessionManager defaultWebSessionManager) {
        //需要获取登录的用户信息
        String header = request.getHeader("X-CskaoyanMarket-Token");
        //需要获取登录的用户信息
        MarketUser marketUser = null;
        Integer userId = 0;
        try {
            Session session = defaultWebSessionManager.getSession(() -> header);
            marketUser = (MarketUser) session.getAttribute(header);
            userId = marketUser.getId();
        } catch (Exception e) {
            return userId;
        }finally {
            return userId;
        }
    }
}
